package Java100_1006;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    //实现根据用户名找密码这样一个过程（用户名 唯一）
    public User selectByName(String name){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where username=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                //存在这个用户，返回一个User对象
                //判断这个用户是普通用户还是管理员
                boolean isAdmin = (resultSet.getInt("isAdmin"))==1;
                User user = null;
                if (isAdmin){
                    user = new Admin();
                }else{
                    user = new NormalUser();
                }
                user.setUserId(resultSet.getInt("userId"));
                user.setUserName(resultSet.getString("username"));
                user.setPassWord(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
}
